import React, { useEffect, useState } from "react";
import {
  Button,
  Table,
  Modal,
  Form,
  Input,
  Space,
  Popconfirm,
  message,
  Select,
  Pagination,
  Card,
  Typography,
} from "antd";
import type { ColumnsType } from "antd/es/table";
import { subjectStudentApi, subjectApi, studentApi } from "../../services/api";

const { Title } = Typography;

interface SubjectStudent {
  id: number;
  subjectId: number;
  studentId: number;
  subjectName?: string;
  studentName?: string;
}

interface Subject {
  id: number;
  name: string;
}

interface Student {
  id: number;
  name: string;
}

const SubjectStudentPage: React.FC = () => {
  const [subjectStudents, setSubjectStudents] = useState<SubjectStudent[]>([]);
  const [subjects, setSubjects] = useState<Subject[]>([]);
  const [students, setStudents] = useState<Student[]>([]);
  const [loading, setLoading] = useState(false);
  const [open, setOpen] = useState(false);
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState<number | null>(null);
  const [pageTotal, setPageTotal] = useState<number>(0);

  const columns: ColumnsType<SubjectStudent> = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "课程ID",
      dataIndex: "subjectId",
      key: "subjectId",
    },
    {
      title: "课程名称",
      dataIndex: "subjectName",
      key: "subjectName",
    },
    {
      title: "学生ID",
      dataIndex: "studentId",
      key: "studentId",
    },
    {
      title: "学生姓名",
      dataIndex: "studentName",
      key: "studentName",
    },
    {
      title: "操作",
      key: "action",
      render: (_, record) => (
        <Space size="middle">
          <Popconfirm
            title="确定从此课程中移除此学生吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <a>移除</a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  const fetchSubjectStudents = async () => {
    setLoading(true);
    try {
      const response = await subjectStudentApi.selectPage({
        pageNum: 1,
        pageSize: 1000,
      });
      setSubjectStudents(response.data.list || []);
    } catch (error) {
      message.error("获取选课列表失败");
    } finally {
      setLoading(false);
    }
  };

  const fetchSubjects = async () => {
    try {
      const response = await subjectApi.selectAll();
      setSubjects(response.data || []);
    } catch (error) {
      message.error("获取课程列表失败");
    }
  };

  const fetchStudents = async () => {
    try {
      const response = await studentApi.selectAll();
      setStudents(response.data || []);
    } catch (error) {
      message.error("获取学生列表失败");
    }
  };

  const handleDelete = async (id: number) => {
    try {
      await subjectStudentApi.remove({ id });
      message.success("移除成功");
      fetchSubjectStudents();
    } catch (error) {
      message.error("移除失败");
    }
  };

  const handleAdd = () => {
    setEditingId(null);
    form.resetFields();
    setOpen(true);
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      await subjectStudentApi.add(values);
      message.success("添加成功");
      setOpen(false);
      fetchSubjectStudents();
    } catch (error) {
      message.error("操作失败");
    }
  };

  const handleCancel = () => {
    setOpen(false);
  };

  const fetchSubjectStudentsByPage = async (
    current: number,
    pageSize: number
  ) => {
    setLoading(true);
    try {
      const response = await subjectStudentApi.selectPage({
        pageNum: current,
        pageSize,
      });
      setSubjectStudents(response.data.list || []);
      setPageTotal(response.data.total);
    } catch (error) {
      message.error("获取选课列表失败");
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchSubjectStudentsByPage(1, 10);
    fetchSubjects();
    fetchStudents();
  }, []);

  function onShowSizeChange(current: number, size: number): void {
    // 分页查询逻实现
    fetchSubjectStudentsByPage(current, size);
  }

  return (
    <div>
      <Card
        title={
          <Title level={4} style={{ margin: 0, color: "#0052D9" }}>
            选课管理
          </Title>
        }
        extra={
          <Button type="primary" onClick={handleAdd}>
            添加选课
          </Button>
        }
        style={{ padding: 0 }}
      >
        <Table
          columns={columns}
          dataSource={subjectStudents}
          loading={loading}
          rowKey="id"
          pagination={false}
        />

        <div
          style={{
            padding: "16px",
            display: "flex",
            justifyContent: "flex-end",
          }}
        >
          <Pagination
            showSizeChanger
            onShowSizeChange={onShowSizeChange}
            defaultCurrent={1}
            total={pageTotal}
            onChange={fetchSubjectStudentsByPage}
            showTotal={(total) => `共 ${total} 条记录`}
          />
        </div>
      </Card>

      <Modal
        title="添加选课"
        open={open}
        onOk={handleOk}
        onCancel={handleCancel}
        okText="确定"
        cancelText="取消"
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="subjectId"
            label="课程"
            rules={[{ required: true, message: "请选择课程" }]}
          >
            <Select>
              {subjects.map((subject) => (
                <Select.Option key={subject.id} value={subject.id}>
                  {subject.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="studentId"
            label="学生"
            rules={[{ required: true, message: "请选择学生" }]}
          >
            <Select>
              {students.map((student) => (
                <Select.Option key={student.id} value={student.id}>
                  {student.name}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default SubjectStudentPage;
